//设置全屏地图
$(window).ready(function(){

var img_data = '';

$(".map").css({"width":$(window).width()-2+"px","height":$(window).height()-60+"px"});
$("body").css({"height":"100%"});

//地图开始
var map = new BMap.Map("container");
var gc = new BMap.Geocoder();       // 创建Map实例
var point = new BMap.Point(106.404, 33.915);
map.centerAndZoom(point,6); 
map.enableKeyboard();
//map.enableScrollWheelZoom();
//map.addControl(new BMap.NavigationControl( {anchor: BMAP_ANCHOR_TOP_RIGHT, offset: new BMap.Size(40, 50),type: BMAP_NAVIGATION_CONTROL_SMALL})); 
map.addControl(new BMap.MapTypeControl({anchor: BMAP_ANCHOR_TOP_RIGHT, offset: new BMap.Size(30, 10)}));
map.addEventListener("dragend",refreshImage);
map.addEventListener("zoomend",refreshImage);

function refreshImage(){
	//map.clearOverlays(); 
  var center = map.getCenter();
  var bound = map.getBounds();
  var x_x = (bound._neLng - bound._swLng)/2;
  var x_y = (bound._neLat - bound._swLat)/2;
  re_value=getImgInfo(1336,30,center.lng,center.lat,x_x,x_y);
  addImage(re_value);
}
	
function temp(obj){
	var attrs = "";
	for(var key in obj){//obj是目标对象
  	attrs += key+":"+obj[key]+"\n";
	}
	//alert(attrs);
	$(".in_content").html(attrs);
}


/*获取图片信息
repuest 都是1336,用于识别请求
num 要求返回的图片数,不够则只返回满足条件的图片
lng 要返回图片的中心坐标经度
lat 要返回图片的中心坐标纬度
x_x 当前视野的经度的一半
x_y 当前视野的纬度的一半
*/
function getImgInfo(repuest,num,lng,lat,x_x,x_y){
	var temp
	$.ajax({url:"ajax/map.pic.php",
		data:{repuest:repuest,limit:num,lng:lng,lat:lat,x:x_x,y:x_y,finish:$.cookie("kuaipaila_finish")},
		dataType : 'json',async:false,success:function(result){
		//alert(result);
		temp=result;
	}});
	return temp;
}

//添加图片
function addImage(re_value){
	//alert(re_value);

	if(re_value!=""){
		$(".in_content").empty();
		$(".message_index").remove();
		map.clearOverlays(); 
		img_data = '';
		
		var marker=new Array();
		var mar=new Array();
		var infoWindow=new Array();
		var iframesrc = new Array();
		var image = new Array();
		
		for(var i=0;i<re_value.length;i++){
			var imagesrc = "image.php?id="+re_value[i].id+"&type=big";
//			var opts={
//				width:imageWidth(imagesrc)+10,
//				height:imageHeight(imagesrc)/2+10
//				}
			
			/*
			填充左边的信息栏
			*/
			var finished = (re_value[i].finished == 0) ? '未解决' : '已解决';
			var html = '<div class="image_content"><input type="hidden" class="this_id" value='+re_value[i].id+'><input type="hidden" class="this_finished" value='+re_value[i].finished+'><input type="hidden" class="lng" value='+re_value[i].lng+'><input type="hidden" class="lat" value='+re_value[i].lat+'><div class="in_content_imgname">'+re_value[i].name+'</div><div style="width:300px;float:left;font-size:14px;"><p class="fl">上传地点：</p><div class="in_content_ico"></div>'+re_value[i].address+'</div><div style="width:100px;float:right"><img style="width:80px;height:80px" src="image.php?id='+re_value[i].id+'&type=small"></div><div style="width:300px;float:left;font-size:14px;"><p class="fl">上传时间：</p>'+re_value[i].post_time+'</div><div style="width:300px;float:left;font-size:14px;">关注('+re_value[i].like_num+')&nbsp;&nbsp;&nbsp;'+finished+'</div></div>';
			$(".in_content").append(html);
			img_data += html;
			
			/*略缩图
			这里是做的假的，用两层实现
			先添加图片，再用边框覆盖图片达到效果
			anchor:图标相对于地理位置的偏移量，单位:PX
			*/
			var pt = new BMap.Point(re_value[i].lng, re_value[i].lat);
			var myIcon = new BMap.Icon("image.php?id="+re_value[i].id+"&type=small", new BMap.Size(60,60),{
				anchor: new BMap.Size(30,82)				
				});
			var marker = new BMap.Marker(pt,{icon:myIcon});  // 创建标注
			map.addOverlay(marker);
			//标注边框对应的图片对象
			image[i]=marker;
			//略缩图边框
			var myIcon = new BMap.Icon("img/map_1.png", new BMap.Size(70,89),{
				anchor: new BMap.Size(35,89)
			});
			var marker = new BMap.Marker(pt,{icon:myIcon});  // 创建标注
			map.addOverlay(marker);              // 将标注添加到地图中

			
			//大图片原代码
			var html = '<div class="index_tck"><div class="index_img_addr">'+re_value[i].address+'</div><div class="index_img_info"><div class="index_img"><a href="" class="dib"><img src="image.php?id='+re_value[i].id+'&type=media" alt="" style="max-width:160px;max-height:160px;border:1px solid #ccc;" /></a></div><div class="index_img_infor"><p href="" class="index_img_title">'+re_value[i].name+'</p><p class="index_img_time">上传时间：<a class="index_astyle" href="">'+re_value[i].post_time+'</a></p><p class="index_img_user">拍摄者：<a class="index_astyle" href="">'+re_value[i].user_name+'</a></p><a href="" class="index_care index_astyle">'+finished+'</a><a href="" class="index_care index_astyle">关心（'+re_value[i].like_num+'）</a></div></div></div>';
			infoWindow[i] = html;
			iframesrc[i] = re_value[i].id;
			mar[i]=marker;
			
		}
		
		for(var i=0;i<mar.length;i++){
		  mar[i]._infoWindow = infoWindow[i];
		  mar[i]._iframesrc = iframesrc[i];
		  mar[i]._image = image[i];
		  mar[i].addEventListener("click",_openInfoWindow);
		  mar[i].addEventListener("mouseover",_show);
		  mar[i].addEventListener("mouseout",_hide);
		}
	}else{
		//如果返回的数据为空
		$(".in_content").animate({left:"-460px"},300);//隐藏信息栏
		map.clearOverlays(); 
//		var center = map.getCenter();
//		var points= new BMap.Point(center.lng,center.lat);
//		gc.getLocation(points, function(rs){
//    	var addComp = rs.addressComponents;
//    	var add= new String;
//    	add = ""+addComp.province +  addComp.city +  addComp.district + addComp.street + addComp.streetNumber+"";					
//			var infoWindow1 = new BMap.InfoWindow("提示：<br>该地区附近还没有上传图片,<a target='_blank' href='post_temp.php?lng="+center.lng+"&lat="+center.lat+"&address="+add+"'>点击上传</a>");  // 创建信息窗口对象
//			map.openInfoWindow(infoWindow1,points);
//   	 });
		message("该地区附近还没有图片");
		}
	
}

function _show(){
  this.setZIndex(11);
  this._image.setZIndex(10);
  //temp(this.siblingElement.offsetLeft);
  var xx = $(this.domElement).offset().left;
  //alert($(this.domElement).offset().left);
  var xy = $(this.domElement).offset().top-$(window).scrollTop();
  var bot = $(window).height()-xy;
  var tx,ty;
  if(xx < 405 && bot > 246 && xy > 80){tx = xx + 71;ty = xy}
  else if(xx < 405 && bot < 246){tx = xx + 71;ty = $(window).height()-246}
  else if(xx < 405 && xy < 80){tx = xx + 71;ty = 80}
  else if(xx > 405 && bot > 246 && xy > 80){tx = xx - 395;ty = xy}
  else if(xx > 405 && bot < 246){tx = xx - 395;ty = $(window).height()-246}
  else if(xx > 405 && xy < 80){tx = xx - 395;ty = 80}
  else{tx = xx - 395;ty = xy}
  $(".index_tck").stop().remove();
  $("body").append(this._infoWindow);
  $(".index_tck").hide().css({left:tx,top:ty}).fadeTo(100,1);
  
  //动画效果
  //this.setAnimation(BMAP_ANIMATION_DROP);
  //this._image.setAnimation(BMAP_ANIMATION_DROP);
 }
 
function _hide(){
	$(".index_tck").stop().fadeTo(100,0,function(){$(".index_tck").remove()});
  this.setZIndex(-6643826);
  this._image.setZIndex(-6643826);
 }

function _openInfoWindow(){ 
//	$(".map_img img").die();             
//  $(".map_img").remove();
//	$("body").append(this._infoWindow);
//	$(".map_img").css({"position":"absolute","left":"410px","top":"110px","z-index":"500",cursor:"move","-webkit-box-shadow":""}).die("mousedown");
//	$("#img").css({position:"absolute",left:"0px",top:"0px"});
//	
//	$(".close img").css({cursor:"pointer"});
//	$(".map_img").hide().fadeTo(300,1,function(){
//		//图片自由拖动效果
//		var xx,xy;
//		$(".map_img img").live('mousedown',function(e){
//			$(".map_img img").one('mouseup',function(){
//				$(".map_img img").die("mousemove");
//				return false;
//			});
//			xx = e.pageX;
//			xy = e.pageY;
//			$(".map_img img").live('mousemove',function(e){
//				var imgx = $(".map_img").offset().left;
//				var imgy = $(".map_img").offset().top;
//				$(".map_img").css({left:imgx+(e.pageX-xx)+"px",top:imgy-(xy-e.pageY)+"px"});
//				xx = e.pageX;
//				xy = e.pageY;
//				return false;
//			});
//			return false;
//		});
//	});
	
	//点击查看大图信息栏相应变化
	$.ajax({url:"index_img_info.php",data:{id:this._iframesrc},type:"POST",dataType:"html",success:function(re){
		$(".in_content").empty().html(re);
		$(".message_index").remove();
		setTimeout(function(){
			xmessage('上传您所拍到的关于此问题的最新情况',$(".update").offset().top, 460, 150, 499,'#222','#eee',1);
			xmessage('我们不会泄露任何关于您的信息，登录是为了能够及时给您反馈',$(".comment").offset().top, 460, 230, 499,'#222','#eee',1);
		},1000);
	}});
	
	$(".in_content,.near_pic").animate({left:"0px"},300);
	$(".content_hide").data("content_hide",1).html("<<").attr("title","收起").animate({left:"432px"},300);
	return false;
}



function fRandomBy(under, over){ 
	switch(arguments.length){ 
		case 1: return parseInt(Math.random()*under+1); 
		case 2: return parseInt(Math.random()*(over-under+1) + under); 
		default: return 0; 
	}
}

function G(id) {
  return document.getElementById(id);
}

var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
    {"input" : "search",
    	"location" : map
});

ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
var str = "";
    var _value = e.fromitem.value;
    var value = "";
    if (e.fromitem.index > -1) {
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }    
    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
    value = "";
    if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }    
    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
    //G("searchResultPanel").innerHTML = str;
});

var myValue;

$("#do_searchs").live('click',function() {    //鼠标点击搜索后的事件,其他页面有不同的处理
    myValue = $("#search").val();
    //G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
    setPlace1();
});


////初始化地图位置
$.ajax({url:"index.class.php",data:{request:1},async:false,success:function(re){
	myValue = re;
}});
if(myValue)setPlace1();


ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
var _value = e.item.value;
    myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    //G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
    setPlace();
});

function setPlace(){
    map.clearOverlays();    //清除地图上所有覆盖物
    function myFun(){
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 15);
        refreshImage();
        //map.addOverlay(new BMap.Marker(pp));    //添加标注
    }
    var local = new BMap.LocalSearch(map, { //智能搜索
      onSearchComplete: myFun
    });
    local.search(myValue);
}

function setPlace1(){
    map.clearOverlays();    //清除地图上所有覆盖物
    function afterSearch(){
      var pp = local.getResults().getPoi(0).point;
      map.centerAndZoom(pp, 15);    //获取第一个智能搜索的结果
    	refreshImage();
    	}
    var local = new BMap.LocalSearch(map, {
    	onSearchComplete: afterSearch
		});
    local.search(myValue);
    
}

function xmessage(message,_top,_left,_width,_index,color,bcolor,opacity){
	var hide = $('<div class="message_hide" title="收起"><</div>');
	var message = $('<div class="message_index"><div style="width:'+(_width-15)+'px;">'+message+'</div></div>');
	$("body").append(message);
	message.css({top:_top+"px",left:_left+"px",width:_width+"px","z-index":_index,"background-color":bcolor,filter:"alpha(opacity="+opacity+")","-moz-opacity":1-opacity,opacity:opacity,color:color}).append(hide);
	hide.css({"padding-top":(hide.parent().innerHeight()-24)/2+"px","padding-bottom":(hide.parent().innerHeight()-24)/2+"px",color:"#fff"});
}

function content_click(){
	$(".message_index").remove();
	if(!$(".content_hide").data("content_hide") || $(this).data("content_hide") == 0){
		$(".content_hide").data("content_hide",1).html("<<").attr("title","收起").animate({left:"432px"},300);
		$(".in_content,.near_pic").animate({left:"0px"},300);
	}else{
		$(".content_hide").data("content_hide",0).html(">>").attr("title","展开").animate({left:"0px"},300);
		$(".in_content,.near_pic").animate({left:"-460px"},300);
	}
	
}

//收起信息小窗口
$(".message_hide").live('click',function(){
	if(!$(this).data("index_hide") || $(this).data("index_hide") == 0){
		$(this).data("index_hide",1).html(">");
		$(this).parent().animate({left:$(this).parent().offset().left-$(this).parent().outerWidth(true)+20+"px"},300);
	}else{
		$(this).data("index_hide",0).html("<");
		$(this).parent().animate({left:$(this).parent().offset().left+$(this).parent().outerWidth(true)-20+"px"},300);
	}
});

//加载数据
refreshImage();

//页面数据初始化
//因为百度API在实例化地图时会重写position属性，所以要最后在改成fixed
$(".map").css({"position":"fixed","z-index":"10",top:"80px"});
$(".he_co").css({position:"fixed","z-index":"501"});
//信息栏
$(".in_content").css({"min-height":$(window).height()-110+"px"});

//工具栏
var tools = '<div class="tools show_china" title="返回全国视图">全国视图</div>';
$("body").append(tools);
$(".show_china").live('click',function(){
	var point = new BMap.Point(106.404, 33.915);
	map.centerAndZoom(point,6); 
});

//附近图片
var nearpic = '<div class="tools near_pic">附近图片</div>';
$("body").append(nearpic);
$(".near_pic").live('click',function(){
	$(".message_index").remove();
	$(".in_content").empty().html(img_data).animate({left:"0px"},300);
});

//收起信息栏
var content_hide = '<div class="tools content_hide" title="展开">>></div>';
$("body").append(content_hide);
$(".content_hide").css({bottom:"0px",left:"0px","background-color":"#000",opacity:".9",padding:"0 5px"}).live('click',function(){content_click();});


//只看已解决
var finished = '<div class="tools finished_only" title="只显示已解决">仅已解决</div>';
//只看未解决
var no_finished = '<div class="tools no_finished_only" title="只显示未解决">仅未解决</div>';
if($.cookie("kuaipaila_finish") == 0 || !$.cookie("kuaipaila_finish"))
$("body").append(finished);
else $("body").append(no_finished);
$(".finished_only").live('click',function(){
	$(this).remove();
	$("body").append(no_finished);
	$.cookie("kuaipaila_finish",1);
	refreshImage();
});

//放大缩小地图
var zoomin = '<div class="zoomin" style="top:140px" title="放大地图"></div>';
var zoomout = '<div class="zoomout" style="top:180px" title="缩小地图"></div>';
$("body").append(zoomin+zoomout);
$(".zoomin").live('click',function(){
	map.zoomIn();
});
$(".zoomout").live('click',function(){
	map.zoomOut();
});


$(".no_finished_only").live('click',function(){
	$(this).remove();
	$("body").append(finished);
	$.cookie("kuaipaila_finish",0);
	refreshImage();
});


//点击信息栏条目
$(".image_content").live('click',function(){
	var lng = $(this).find(".lng").val();
	var lat = $(this).find(".lat").val();
	var point = new BMap.Point(lng, lat);
	map.centerAndZoom(point,15);
	$.ajax({url:"index_img_info.php",data:{id:$(this).find(".this_id").val()},type:"POST",success:function(re){
		$(".in_content").empty().html(re);
		setTimeout(function(){
			xmessage('上传您所拍到的关于此问题的最新情况',$(".update").offset().top, 460, 150, 499,'#222','#eee',1);
			xmessage('我们不会泄露任何关于您的信息，登录是为了能够及时给您反馈',$(".comment").offset().top, 460, 230, 499,'#222','#eee',1);
		},1000);
	}});
	$(".message_index").remove();
	$(".in_content").animate({left:"0px"},300);
	return false;
})


});

//查看原图的效果
function original(obj){
	var $original = $('<img src="img/original.png" title="查看原图" class="img_original">');
	$(".in_content").append($original);
	$original.css({position:"absolute",left:$(obj).position().left+$(obj).width()+"px",top:$(obj).position().top+"px",cursor:"pointer",opacity:".7"});
	
	$original.hover(function(){
		$(this).css({opacity:"1"});
	},function(){
		$(this).css({opacity:".7"});
	});
	
	$original.click(function(){
		var ssrc = $(obj).attr("src").replace(/media/,"original");
		$("body").append('<div class="full"></div>').css({overflow:"hidden"});
		$(".full").css({position:"absolute",top:$(window).scrollTop()+"px"}).append(opacity).append('<img src="'+ssrc+'" style="margin:30px;z-index:1000;position:absolute;max-width:'+($(window).width()-100)+'px;">').append('<div class="close" title="关闭" style="position:fixed;top:0px;right:0px"><a href="" class="cancel_big"></a></div>');
		$(".opacity").animate({top:"0px"},300);;
		$(".opacity").css({"width":$(window).width()+"px","height":$(window).height()+"px","opacity":".9",top:-$(window).height()+"px",overflow:"auto"});
		
	});
}


// 测试插件

// $(window).ready(function(){
// 	var liuzw_zz = '<div class="liuzw_zz_main liuzw_zz_bn"></div>';
// 	$("html,body").append(liuzw_zz);

// 	var liuzw_data = new Array();
// 	var b_g = 5;//方块之间的间隔 PX
// 	liuzw_data[1] = new Array();
// 	liuzw_data[2] = new Array();
// 	$(".liuzw_zz ul").each(function(){
// 		// alert($(this).attr("liuzw_val"));
// 		var obj = $(this);
// 		liuzw_data[1].push(obj.attr("liuzw-val"));
// 		obj.find("li").each(function(){
// 			liuzw_data[2].push($(this).html());
// 		})
// 	});

// 	for(var i=0;i<liuzw_data[1].length;i++){
// 		var class_name = 'liuzw_zz_1_'+(i+1);
// 		var html = '<div class="'+class_name+' liuzw_zz_bn"></div>';
// 		$("html,body").append(html);
// 		$("."+class_name).css({position:"fixed","z-index":6661+i}).hide();
// 	}
	
// 	$(".liuzw_zz_bn").css({position:"fixed",top:"200px",right:"150px",height:"52px",width:"60px","background":"url(img/zz.png)","cursor":"pointer",opacity:"0.8"});
// 	$(".liuzw_zz_main").css({"z-index":"7000"});
// 	// 计算部分
// 	main = $(".liuzw_zz_main");
// 	var s_m = 1.4142135623731+1+1;
// 	var b_h = main.height(),b_w = main.width();
// });